# coding:utf-8
import time

import pandas as pd
from xtquant import xtdata, xttrader
import backtesting
from strategy import SignGeneration

# 没看到回调函数如何传参，只能写全局变量
backtest = backtesting.Backtesting(fund=10000000, debuginfo=False, lowest_sell_thd=0)
sign_genrator = SignGeneration()
print("初始化全局变量")


#订阅最新行情
def callback_func_test(data):
    print(data)
    # data = xtdata.get_market_data(['close'], [code], period='1m', start_time='20230701')
    data = pd.Series(data["513130.SH"][0]).to_frame().T
    # print('回调数据', data["time"])
    # print(data.columns)
    # data.to_csv("data.csv_sample")
    data.to_csv("data.csv", mode="a", columns=data.columns, header=0, index=False)
    # data = pretreatment(data)  # 获取数据预处理
    return 1


def pretreatment(code, raw_series):
    # print("raw_series = ", raw_series)
    series = pd.Series()
    # 预处理字段为 'code', 'date', 'open', 'high', 'low', 'close', 'volume', 'turnover', 'factor', 'code_name', '日期'
    series["code"] = code
    series["date"] = pd.to_datetime(raw_series["time"], unit='ms')
    series["open"] = raw_series["open"]
    series["high"] = raw_series["high"]
    series["low"] = raw_series["low"]
    # series["close"] = raw_series["lastClose"]
    # series["成交价"] = raw_series["lastClose"]
    series["close"] = raw_series["close"]
    series["成交价"] = raw_series["close"]
    series["volume"] = raw_series["amount"]
    # print(series["date"])
    series["日期"] = series["date"].strftime("%Y%m%d")
    return series


def callback_func(data, type="tick"):
    for code in data.keys():
        print(">>>>> start >>>>> ")
        print(data[code])
        raw_series = pd.Series(data[code][0])  # 数据获取
        current_series = pretreatment(code, raw_series)  # 数据预处理   tick/1m/5m/1d
        backtest.backtesting_sim(code, current_series, sign_genrator)  # 调用方法  模拟/实盘

def sim_callback_data(file):
    data = pd.read_csv(file)
    for index in data.index:
        yield data.loc[index, :]


if __name__ == '__main__':
    # 参数初始化 -------------
    code = '513180.SH'

    # 测试订阅模式 开始 ----------------------
    # xtdata.subscribe_quote(code, period='tick', count=-1, callback=callback_func_test)
    # xtdata.run()
    # 测试订阅模式 结束 -----------------------

    # 实时模拟盘 实时模拟盘开始 ----------------------
    xtdata.subscribe_quote(code, period='tick', count=-1, callback=callback_func)
    xtdata.run()
    # 实时模拟盘 模拟数据处理结束 ----------------------


    # 实时模拟盘 模拟数据处理开始 ----------------------
    # file = "data.csv"
    # for series in sim_callback_data(file):
    #     # print(series)
    #     dict1 = {"513130.SH": [dict(series)]}
    #     print(dict1)
    #     callback_func(dict1)
    #     time.sleep(1)

    # 实时模拟盘 模拟数据处理结束 ----------------------
